package com.baofu.paycore.service.validate.impl.preAuth;

import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.manager.model.PayBaseBO;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.common.utils.Constant;
import com.baofu.paycore.manager.model.preAuth.PreAuthBO;
import com.baofu.paycore.manager.storer.PreAuthRepository;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.authconfirm.AuthConfirmDTO;
import com.baofu.paycore.service.validate.AbstractPayValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 预授权确认校验
 *
 * User: xin deng  Date: 16/8/31 ProjectName: paycore Version: 1.0
 */
@Slf4j
@Service
public class PreAuthConfirmValidate extends AbstractPayValidate<AuthConfirmDTO> {

    /**
     * 订单唯一性校验
     *
     * @param authConfirmDTO     被校验对象
     */
    public PreAuthBO validateUniqueOrder(AuthConfirmDTO authConfirmDTO, PreAuthRepository preAuthRepository) {

        if (!authConfirmDTO.getAmt().equals(authConfirmDTO.getFundDetailInfoDTO().getPayToolAmount())) {
            log.error("预授权完成金额:{} 资金单中金额:{}", authConfirmDTO.getAmt(),
                    authConfirmDTO.getFundDetailInfoDTO().getPayToolAmount());
            throw new PayCoreBizException(PayCoreErrorCode.AMT_IS_NOT_IN_CONFORMITY, "预授权完成金额与资金单金额不一致");
        }
        PayBaseBO order = preAuthRepository.checkIdempotent(authConfirmDTO.getRequestBizNo(),
                authConfirmDTO.getRequestOrderNo(),authConfirmDTO.getRequestSystem());
        if (order != null) {
            log.error("预授权完成订单已存在:{},{}", authConfirmDTO.getRequestBizNo(), authConfirmDTO.getRequestOrderNo());
            throw new PayCoreBizException(PayCoreErrorCode.ORDER_EXITS);
        }
        //查询原单信息
        PreAuthBO preAuthBO = preAuthRepository.getPreAuthByOrigPayNo(authConfirmDTO.getOrigPayNo());
        if (preAuthBO == null) {
            log.error("预授权单不存在 原支付单号:{}", authConfirmDTO.getOrigPayNo());
            throw new PayCoreBizException(PayCoreErrorCode.PRE_AUTH_ORDER_NO_EXIST);
        }
        if (!PayStatusEnums.SUCCESS.getCode().equals(preAuthBO.getStatus())) {
            log.error("预授权订单状态不成功 不能完成 支付单号:{} 状态:{}", preAuthBO.getPayNo(), preAuthBO.getStatus());
            throw new PayCoreBizException(PayCoreErrorCode.PRE_AUTH_ORDER_NO_SUC);
        }
        long bizChargeAmount = Constant.validateLong(authConfirmDTO.getFundDetailInfoDTO().getBizChargeAmount());
        if (preAuthBO.getAmt()- Constant.validateLong(preAuthBO.getDealAmt())
                < authConfirmDTO.getAmt() + bizChargeAmount) {
            log.error("预授权完成金额大于可预授权金额 订单号:{} 预授权总金额:{} 预授权完成金额:{} 手续费金额:{}", preAuthBO.getPayNo(),
                    preAuthBO.getAmt(), authConfirmDTO.getAmt(), bizChargeAmount);
            throw new PayCoreBizException(PayCoreErrorCode.OVERRUN_CONFIRM_AMOUNT);
        }
        return preAuthBO;
    }
}
